import 'dart:io';

import 'package:flutter/services.dart';

import '../index.dart';

class DomainPage extends StatefulWidget {
  const DomainPage({Key? key}) : super(key: key);

  @override
  _DomainState createState() => _DomainState();
}

class _DomainState extends State<DomainPage> {
  final TextEditingController _apiController = TextEditingController();

  // final TextEditingController _imgController = TextEditingController();
  final TextEditingController _proxyController = TextEditingController();
  bool _switchUseProxy = true;
  final String regExpHttp = r"^(http|https)\://([\s\S]*)";
  final String regExpIp =
      r"^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$";

  final GlobalKey _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    // 自动填充sit环境域名
    _apiController.text = Global.profile.apiDomain;
    // _imgController.text = Global.profile.imgDomain;

    _switchUseProxy = Global.profile.isUseProxy;
    _proxyController.text = Global.profile.proxy;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var s = S.of(context);
    var children = <Widget>[
      TextFormField(
          controller: _apiController,
          decoration: const InputDecoration(
            labelText: "接口域名",
            hintText: "请输入接口域名",
            prefixIcon: Icon(Icons.api),
          ),
          // 校验用户名（不能为空）
          validator: (v) {
            if (!RegExp(regExpHttp).hasMatch(v!)) {
              return "请输入正确域名！";
            }
            return null;
          }),
      Padding(
        padding: EdgeInsets.all(5),
        child: Text("快捷切换"),
      ),
      Row(
        children: [
          Expanded(
            child: TextButton(
                onPressed: () {
                  setState(() {
                    _apiController.text =
                        "http://light.saas.sit.guoxintianyu.com/api";
                  });
                },
                child: Text("sit")),
          ),
          Expanded(
            child: TextButton(
                onPressed: () {
                  setState(() {
                    _apiController.text =
                        "http://light.saas.uat.guoxintianyu.com/api";
                  });
                },
                child: Text("uat")),
          ),
          Expanded(
            child: TextButton(
                onPressed: () {
                  setState(() {
                    _apiController.text =
                        "http://light.saas.pro.guoxintianyu.com/api";
                  });
                },
                child: Text("pro")),
          ),
        ],
      ),
      const Divider(
        height: 1,
      ),
      // TextFormField(
      //   controller: _imgController,
      //   decoration: const InputDecoration(
      //     labelText: "图片域名",
      //     hintText: "请输入图片域名",
      //     prefixIcon: Icon(Icons.image),
      //   ),
      //   //校验密码（不能为空）
      //   validator: (v) {
      //     if (!RegExp(regExpHttp).hasMatch(v!)) {
      //       return "请输入正确域名！";
      //     }
      //     return null;
      //   },
      // ),
      Padding(
        padding: EdgeInsets.all(5),
        child: Row(
          children: [
            Text("开启代理"),
            Switch(
              value: _switchUseProxy, //当前状态
              onChanged: (value) {
                //重新构建页面
                setState(() {
                  _switchUseProxy = value;
                });
              },
            ),
          ],
        ),
      )
    ];
    if (_switchUseProxy) {
      children.add(TextFormField(
        controller: _proxyController,
        decoration: InputDecoration(
          labelText: "代理地址",
          hintText: "请输入代理地址",
          prefixIcon: const Icon(Icons.compare_arrows),
        ),
        //校验密码（不能为空）
        validator: (v) {
          if (!RegExp(regExpIp).hasMatch(v!)) {
            return "请输入正确的代理地址！";
          }
          return null;
        },
      ));
    }
    children.add(
      Padding(
        padding: const EdgeInsets.only(top: 25),
        child: ConstrainedBox(
          constraints: const BoxConstraints.expand(height: 55.0),
          child: ElevatedButton(
            onPressed: _onSave,
            child: Text(
              s.saveAndExit,
            ),
          ),
        ),
      ),
    );
    children.add(
      Padding(
        padding: const EdgeInsets.only(top: 25),
        child: ConstrainedBox(
          constraints: const BoxConstraints.expand(height: 55.0),
          child: ElevatedButton(
            onPressed: _onTokenTest,
            child: Text("token失效测试"),
          ),
        ),
      ),
    );

    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
          appBar: AppBar(
            title: Text(s.domainSettings),
            centerTitle: true,
          ),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Form(
              autovalidateMode: AutovalidateMode.onUserInteraction,
              child: ListView(children: children),
              key: _formKey,
            ),
          ),
        ),
      ),
    );
  }

  void _onSave() async {
    // 先验证各个表单字段是否合法
    if ((_formKey.currentState as FormState).validate()) {
      //保存域名 并重新设置Dio
      Global.profile.apiDomain = _apiController.text;
      // Global.profile.imgDomain = _imgController.text;
      Global.profile.isUseProxy = _switchUseProxy;
      if (_switchUseProxy) {
        Global.profile.proxy = _proxyController.text;
      }
      Global.saveProfile();

      showToast(S.of(context).saveSuccess);
      // 使用此方法iOS退不出来
      // await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      //延时3秒
      Future.delayed(const Duration(seconds: 1), () {
        exit(0);
      });
    }
  }

  void _onTokenTest() async {
    Global.profile.token = "test";
    Global.profile.user?.accessToken = "test";
    Global.profile.user?.refreshToken = "test";
    Global.saveProfile();
    showToast("设置成功");
  }
}
